package com.springboot.cloud.demos.ribbon.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.springboot.cloud.common.core.entity.vo.Result;
import com.springboot.cloud.common.core.exception.SystemErrorType;
import com.springboot.cloud.demos.entity.form.UserCouponForm;
import com.springboot.cloud.demos.entity.param.UserCouponQueryParam;
import com.springboot.cloud.demos.entity.po.UserCoupon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class UserCouponService {

    @Autowired
    RestTemplate restTemplate;

    @SentinelResource(fallback = "conditionsFallback")
    public Result conditions(@RequestBody UserCouponQueryParam param) {
        return restTemplate.postForEntity("http://producer/userCoupon/conditions", param, Result.class).getBody();
    }

    public Result conditionsFallback(@RequestBody Map params) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "userCouponFallback")
    public Result userCoupon(String userCouponId) {
        return restTemplate.getForEntity("http://producer/userCoupon/{userCouponId}", Result.class, userCouponId).getBody();
    }

    public Result userCouponFallback(@RequestBody Map params) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    @SentinelResource(fallback = "saveFallback")
    public Result save(@RequestBody UserCouponForm userCouponForm) {
        return restTemplate.postForEntity("http://producer/userCoupon", userCouponForm, Result.class).getBody();
    }

    @SentinelResource(fallback = "updateFallback")
    public Result update(@RequestBody UserCouponForm userCouponForm) {
        restTemplate.put("http://producer/userCoupon/{1}", userCouponForm, userCouponForm.getId());
        return Result.success();
    }

    public Result saveFallback(@RequestBody UserCouponForm userCouponForm) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }

    public Result updateFallback(UserCoupon userCoupon) {
        return Result.fail(SystemErrorType.SYSTEM_BUSY);
    }
}
